<template>
  <j-modal
    switchFullscreen
    :width="500"
    :title="title"
    :visible="visible"
    @cancel="handleCancel"
    @ok="handleOk"

    :confirmLoading="confirmLoading"
  >
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button @click="handleOk" type="primary" :loading="confirmLoading" v-if="!disableSubmit">确认</a-button>
    </template>
    <a-form :form="form">
      <a-form-item
        :labelCol="{  xs: { span: 6 },sm: { span: 5 },}"
        :wrapperCol="{ xs: { span:14 }, sm: { span: 18}}"
        label="分类名称"
      >
        <a-input style="width: 100%" :disabled="disableSubmit" placeholder="分类名称"
                 v-decorator="['classifyName', validatorRules.classifyName]"/>
      </a-form-item>
      <a-form-item
        :labelCol="{  xs: { span: 6 },sm: { span: 5 },}"
        :wrapperCol="{ xs: { span:14 }, sm: { span: 18}}"
        label="父级分类"
        v-if="model.classifyLevel=1"
      >
        <a-input-search placeholder="父级分类" v-decorator="[ 'parentClassifyName']" onfocus="this.blur()"
                        @search="productSearch" :disabled="disableSubmit">
          <a-button icon="search" style="color: #2eabce" slot="enterButton">
          </a-button>
        </a-input-search>
        <a-input type="hidden" v-decorator="['parentClassifyCode']"/>
      </a-form-item>
      <a-form-item
        :labelCol="{  xs: { span: 6 },sm: { span: 5 },}"
        :wrapperCol="{ xs: { span:14 }, sm: { span: 18}}"
        label="类型"
      >
        <cn-dict-select-tag v-decorator.trim="['dataType']" :disabled="disableSubmit"
                            :options="{value:'dictDataDesc',label:'dictDataDesc'}"
                            :triggerChange="true" dictCode="classify_data_type"/>
      </a-form-item>
      <a-form-item
        :labelCol="{  xs: { span: 6 },sm: { span: 5 },}"
        :wrapperCol="{ xs: { span:14 }, sm: { span: 18}}"
        label="排序"
        >
        <a-input placeholder="请输入" type="number" :min="0" :disabled="disableSubmit"
                 v-decorator="['sort',validatorRules.sort]"/>
      </a-form-item>

      <a-form-item
        :labelCol="{  xs: { span: 6 },sm: { span: 5 },}"
        :wrapperCol="{ xs: { span:14 }, sm: { span: 18}}"
        label="上传LOGO"
      >
        <JUpload
          :disabled="disableSubmit"
          accept=".png,.jpg,.jpeg"
          v-decorator="['logo']"
          fileType="image"
          class="avatar-uploader"
          :number="1"
          text="产品图片"
          :returnUrl="true"
        />
      </a-form-item>
    </a-form>
    <a-divider style="font-weight: 600;margin-top: 0px;" orientation="left">组织范围</a-divider>
    <a-divider style="font-weight: 400;margin-top: 0px;" orientation="left">包含</a-divider>
    <div>
      <a-button style="margin: 10px 30px 0px 30px;" @click="addInclude" type="primary" v-if="!disableSubmit">新增
      </a-button>
    </div>

    <div style="padding: 10px 20px;">
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :scroll="{x:400,y:240 }"
        :rowSelection="{selectedRowKeys:selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
           <a style="color: red;" @click="handleDelete(record)" v-if="!disableSubmit">删除</a>
        </span>
      </a-table>
    </div>
    <a-divider style="font-weight: 400;margin-top: 30px;" orientation="left">排除</a-divider>
    <div>
      <a-button style="margin: 10px 30px 0px 30px;" @click="addExclude" type="primary" v-if="!disableSubmit">新增
      </a-button>
    </div>
    <div style="padding: 10px 20px;">
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource2"
        :scroll="{x:400,y:240 }"
        :rowSelection="{selectedRowKeys:selectedRowKeys2, onChange: onSelectChange}"
        @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
           <a style="color: red;" @click="handleDelete2(record)" v-if="!disableSubmit">删除</a>
        </span>
      </a-table>
    </div>
    <proChose ref="prochoose" v-bind="modalProps" @okbro="okbropro"></proChose>

    <choose-modal
      ref="chooseModal1"
      :chooseUrl="orgurl"
      :tableFields="orgColumns"
      @choose="okbropro2"
      :removeChildren="true"
      mode="checkbox"
      :searchCondition="[{ label: '组织编号', field: 'orgCode' },{ label: '组织名称', field: 'orgName' }]"
    ></choose-modal>
    <choose-modal
      :removeChildren="true"
      ref="chooseModal2"
      :chooseUrl="orgurl"
      :tableFields="orgColumns"
      @choose="okbropro3"
      mode="checkbox"
      :searchCondition="[{ label: '组织编号', field: 'orgCode' },{ label: '组织名称', field: 'orgName' }]"
    ></choose-modal>
  </j-modal>
</template>

<script>
import chooseModal from '@/components/cn-components/ChooseModal'
import salePlaceCard from '@/components/cn-components/SalePlaceCard.vue'
import JUpload from '@/components/cn-form/JUpload'
import { pick } from 'lodash'
import { getAction, postAction } from '@/api/manage'
import proChose from '@comp/cn-components/ProChose'

import myShuttleModal from '../../../../components/cn-components/CnShuttleModal'

export default {
  name: 'cusproModal',
  components: { myShuttleModal, JUpload, salePlaceCard, proChose, chooseModal },
  data() {
    return {
      orgurl: window._CONFIG['domianURL'] + '/cnOrgController/findTreeList',
      disableSubmit: false,
      disableSubmits: false,
      title: '',
      name: '',
      name2: '',
      showType: 0,
      classifyLevel: 0,
      dataSource: [],
      dataSource2: [],
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      selectedRowKeys2: [],
      /* table选中records*/
      selectionRows2: [],
      confirmLoading: false,
      form: this.$form.createForm(this),
      model: {},
      visible: false,
      loading: false,
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      },
      orgColumns: [
        {
          title: '组织编号',
          align: 'center',
          dataIndex: 'orgCode',
          // width: 120,
          ellipsis: true
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'orgName',
          // width: 120,
          ellipsis: true
        }],
      columns: [
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'orgName'
        },

        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      url: {
        // kuaidi: window._CONFIG['domianOrderURL'] + '/cnDictionaryTypeController/getDictionaryTypeList'
        sendOrder: window._CONFIG['domianURL'] + '/material/saveOrUpdate'
      },
      validatorRules: {
        classifyName: {
          rules: [
            { required: true, message: '' }
          ]
        },
        sort: {
          rules: [
            { required: true, message: '' }
          ]
        },
        remarks: {
          rules: [
            { required: true, message: '' }
          ]
        }
      }
    }

  },
  computed: {
    modalProps() {
      return {
        name: this.name
      }
    },
    modalProps2() {
      return {
        name: this.name2
      }
    }
  },
  methods: {
    okbropro(val, status, status2) {
      let objs = JSON.parse(JSON.stringify(val[0]))
      console.log(objs)
      this.form.setFieldsValue({
        parentClassifyName: objs.classifyName,
        parentClassifyCode: objs.classifyCode,
      })
      this.classifyLevel = objs.classifyLevel
      this.model.parentClassifyCode = objs.classifyCode
    },
    okbropro2(val, status, status2) {
      let key = this.dataSource.map(item => {
        return item.orgCode
      })
      let that = this
      val.forEach(item => {
        if (key.indexOf(item.orgCode) == -1) {
          item.children = undefined
          this.dataSource.push(item)
        }
      })
    },
    okbropro3(val, status, status2) {
      console.log(val)
      let key = this.dataSource2.map(item => {
        return item.orgCode
      })
      let that = this
      val.forEach(item => {
        if (key.indexOf(item.orgCode) == -1) {
          item.children = undefined
          this.dataSource2.push(item)
        }
      })

    },
    handleAdd() {
      this.$refs.shuttleModal.visible = true

    },
    addInclude() {
      // this.$refs.orgChooseok.rowKey = 'id'
      // let formconfig = [
      //   {
      //     key: 'orgCode',
      //     label: '组织编号'
      //   },
      //   {
      //     key: 'orgName',
      //     label: '组织名称'
      //   }
      // ]
      // let tableconfig = {
      //   columns: [
      //     {
      //       title: '组织编号',
      //       align: 'center',
      //       dataIndex: 'orgCode',
      //       // width: 120,
      //       ellipsis: true
      //     },
      //     {
      //       title: '组织名称',
      //       align: 'center',
      //       dataIndex: 'orgName',
      //       // width: 120,
      //       ellipsis: true
      //     }
      //   ],
      //   list: window._CONFIG['domianURL'] + '/cnOrgController/findTreeList',
      //   multiple: true,
      //   columW: 30
      // }
      //
      // this.name2 = '选择组织'
      //
      //
      // this.$refs.orgChooseok.edit(formconfig, tableconfig)
      this.$refs.chooseModal1.show()
    },
    addExclude() {
      this.$refs.chooseModal2.show()
    },
    add() {
      this.visible = true
      this.edit()
    },
    edit(record = {}) {
      this.form.resetFields()
      let that = this
      if (record.cnOrgInfoVos) {
        record.cnOrgInfoVos.forEach(item => {
          if (item.ruleType == 1) {
            that.dataSource.push(item)
          } else {
            that.dataSource2.push(item)
          }
        })
      }
      this.model = Object.assign({}, record)
      this.visible = true
      let fieldsVal = pick(this.model, 'classifyName', 'classifyCode', 'parentId', 'parentClassifyName', 'parentClassifyCode', 'logo', 'sort')
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldsVal)
      })

    },
    cutType(key) {
      if (key == '1') {
        this.showType = false
      } else {
        this.showType = true
      }
    },
    productSearch(status) {
      this.$refs.prochoose.rowKey = 'id'
      let formconfig = [
        {
          key: 'classifyCode',
          label: '分类编号'
        },
        {
          key: 'classifyName',
          label: '分类名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '分类编号',
            align: 'center',
            dataIndex: 'classifyCode',
            width: 120,
            ellipsis: true
          },
          {
            title: '分类名称',
            align: 'center',
            dataIndex: 'classifyName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/goodsclassify/cnGoodsClassify/findPageList',
        multiple: false,
        columW: 10
      }

      this.name = '父类'
      let dataSource = []
      if (this.form.getFieldValue('superiorUser')) {
        dataSource = [{
          userName: this.form.getFieldValue('superiorUser'),
          realName: this.form.getFieldValue('realsname')
        }]
      }
      console.log(dataSource)
      this.$refs.prochoose.edit(formconfig, tableconfig, 'parentClassifyCode', 'orgCode', dataSource)
    },
    handleDelete(e) {

      let key = this.dataSource.map(item => {
        return item.id
      })
      this.dataSource.splice(key.indexOf(e.id), 1)

    },
    handleDelete2(e) {
      let key = this.dataSource2.map(item => {
        return item.id
      })
      this.dataSource2.splice(key.indexOf(e.id), 1)
    },
    chooseOk(e) {
      let key = this.dataSource.map(item => {
        return item.id
      })
      e.forEach(item => {
        // console.log(key.indexOf(item.id),key,item.id)
        if (key.indexOf(item.id) == -1) {
          this.dataSource.push(item)
        }
      })
      // this.dataSource=e
    },

    handleOk() {
      let that = this
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(that.model, values)
          console.log('数据', that.model, values)
          let cnOrgInfoVos = []
          console.log(formData)
          this.dataSource.forEach(item => {
            cnOrgInfoVos.push({ orgCode: item.orgCode, orgName: item.orgName, orgType: item.orgType, ruleType: 1 })
          })
          this.dataSource2.forEach(item => {
            cnOrgInfoVos.push({ orgCode: item.orgCode, orgName: item.orgName, orgType: item.orgType, ruleType: 2 })
          })
          formData.cnOrgInfoVos = cnOrgInfoVos
          formData.classifyLevel = this.classifyLevel
          formData.parentClassifyCode = formData.parentClassifyCode ? formData.parentClassifyCode : formData.classifyCode
          delete formData.classifyCode
          postAction('/goodsclassify/cnGoodsClassify/saveOrUpdate', formData).then((res) => {
            if (res.success) {
              that.$message.success(res.message, 2)
              that.$emit('ok')
              that.close()
            } else {
              that.$message.error(res.message, 2)
            }
          }).finally(() => {
            that.confirmLoading = false
          })

        }
      })
    },

    handleCancel() {
      this.form.resetFields()
      this.visible = false
      this.confirmLoading = false
      this.dataSource = []
      this.dataSource2 = []
    },
    close() {
      this.handleCancel()
    }
  }
}
</script>

<style scoped>

</style>
